// 绑定账户
import express from "express";
import pool from "../importantApi/db_connection.js";

const router = express.Router();
router.post("/", async (req, res) => {
    const {userId, identity, toUserAccount, toUserPassword, toUserIdentity} = req.body;
    if (!userId || !identity || !toUserAccount || !toUserPassword || !toUserIdentity) {
        return res.status(401).json({
            code: 401,
            msg: "缺少必要参数"
        })
    }
    try {
        // 匹配另一个账户登录信息
        let [result] = await pool.query(`
            select user_id, identity
            from userinfo
            where account = '${toUserAccount}'
              and password = '${toUserPassword}'
              and identity = '${toUserIdentity}'`)
        if (result.length === 0) {
            return res.status(401).json({
                code: 201,
                msg: "请核对信息"
            })
        }
        // 检查两个号是否相同
        if (result[0].user_id === userId) {
            return res.status(201).json({
                code: 201,
                msg: "相同账户不可关联"
            })
        }
        // 查询是否已经关联过
        let [result3] = await pool.query(`
            select count(*) as count
            from user_relationship
            where (from_user_id = ${userId}
                and to_user_id = ${result[0].user_id})
               or (to_user_id = ${userId}
                and from_user_id = ${result[0].user_id})
        `)
        if (result3[0].count === 0) {
            // 没有被关联过，则新建关联
            let [result2] = await pool.query(`
                insert into user_relationship (from_user_id, to_user_id, relationship_type)
                values ('${userId}', '${result[0].user_id}', '${identity}_${result[0].identity}')
            `)
            // 关联失败
            if (result2.affectedRows === 0) {
                return res.status(201).json({
                    code: 201,
                    msg: "账户关联失败，请重试"
                })
            }
            return res.status(200).json({
                code: 200,
                msg: "账户关联成功"
            })
        } else {
            return res.status(200).json({
                code: 201,
                msg: "当前账户已经关联"
            })
        }
    } catch (err) {
        console.log(err);
        return res.status(500).json({
            code: 500,
            msg: "关联错误：server error"
        })
    }
})
export default router;